﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace SimpleX
{
    public class JwtHelper
    {
        public static JwtSettings _jwtSettings;

        static JwtHelper()
        {
            _jwtSettings = App.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
        }

        public static string GenerateToken(IEnumerable<Claim> claims)
        {
            /*
             new[]
                {
                     new Claim(ClaimTypes.NameIdentifier, userId)
                }
             */

            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.UTF8.GetBytes(_jwtSettings.Key);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.UtcNow.AddMinutes(_jwtSettings.ExpirationMinutes),
                Issuer = _jwtSettings.Issuer,
                Audience = _jwtSettings.Audience,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
            //return JwtBearerDefaults.AuthenticationScheme + " " + tokenHandler.WriteToken(token);
        }

        public static string GenerateToken(Dictionary<string, string> dicClaims)
        {
            var claims = dicClaims.Select(x => new Claim(x.Key, x.Value));
            return GenerateToken(claims);
        }

        public static bool CheckExp(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            try
            {
                var key = Encoding.UTF8.GetBytes(_jwtSettings.Key);

                var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                if (validatedToken.ValidTo < DateTime.UtcNow)
                    return true;

                return false;

                // 读取 JWT Token 中的信息
                //var jwtTokenInfo = (JwtSecurityToken)validatedToken;
                //var userId = jwtTokenInfo.Claims.First(x => x.Type == "user_id").Value;
            }
            catch (SecurityTokenExpiredException)
            {
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}